package org.vacoor.xqq.ui.comp.textfield;

import org.vacoor.xqq.core.util.ImageResources;
import org.vacoor.xqq.ui.comp.border.RolloverBorder;

import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

/**
 * @author Vacoor
 */
public class IconifyPasswdField extends JPanel {
    private static final long serialVersionUID = 1L;

    private static final Icon KEYBOARD_ICON = ImageResources.getIcon("image/keyboard/keyboard.png");
    private static final Icon KEYBOARD_ROLLOVER_ICON = ImageResources.getIcon("image/keyboard/keyboard_01.png");
    private static final Icon KEYBOARD_PRESSED_ICON = ImageResources.getIcon("image/keyboard/keyboard_02.png");

    private final Dimension size = new Dimension(180, 26);
    private JPasswordField passwdField;
    private JButton buttonKey;

    public IconifyPasswdField() {
        passwdField = new JPasswordField();
        buttonKey = new JButton();

        passwdField.setBorder(BorderFactory.createEmptyBorder(3, 8, 5, 3));
        passwdField.setEchoChar('●');
        buttonKey.setIcon(KEYBOARD_ICON);
        buttonKey.setRolloverEnabled(true);
        buttonKey.setRolloverIcon(KEYBOARD_ROLLOVER_ICON);
        buttonKey.setPressedIcon(KEYBOARD_PRESSED_ICON);

        buttonKey.setContentAreaFilled(false);
        buttonKey.setFocusPainted(false);
        buttonKey.setBorder(null);

        this.setLayout(new BorderLayout());
        this.add(passwdField, BorderLayout.CENTER);
        this.add(buttonKey, BorderLayout.EAST);
        this.setPreferredSize(size);
        this.setBackground(Color.WHITE);

        RolloverBorder border = new RolloverBorder(
                BorderFactory.createCompoundBorder(
                        BorderFactory.createEmptyBorder(1, 1, 1, 1),
                        new LineBorder(new Color(167, 195, 212), 1, true)
                ),
                BorderFactory.createCompoundBorder(
                        new LineBorder(new Color(96, 200, 253), 1, true),
                        new LineBorder(new Color(51, 139, 192), 1, true))
        );
        this.setBorder(border);
        border.addTrigger(passwdField, buttonKey);

        this.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                passwdField.setFont(passwdField.getFont().deriveFont(IconifyPasswdField.this.getHeight() - 10F));
            }
        });
    }

    public JPasswordField getPasswdField() {
        return this.passwdField;
    }

    public char[] getPassword() {
        return passwdField.getPassword();
    }

    public void clear() {
        passwdField.setText("");
    }
}
